package net.oschina.dajiangnan.wx.process.pay.tools;

import java.text.ParseException;

import javax.servlet.http.HttpServletRequest;

import net.oschina.dajiangnan.util.XStreamHelper;
import net.oschina.dajiangnan.wx.util.DateUtil;
import net.oschina.dajiangnan.wx.util.HttpTookit;
import net.oschina.dajiangnan.wx.util.RandomUtil;
import net.oschina.dajiangnan.wx.util.Signature;
import org.apache.log4j.Logger;

import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.constants.PathDefine;
import net.oschina.dajiangnan.wx.process.pay.Scan_qrcode_notify;
import net.oschina.dajiangnan.wx.process.pay.bean.Product;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.UnifiedorderReq;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.UnifiedorderResp;


public class Unifiedorder {

    private static Logger logger = Logger.getLogger(Scan_qrcode_notify.class);

    
    private static final String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    
    
    private static final int unified_order_time_expire = 10;//minute
    
    
    
    public static Result get(HttpServletRequest req,String openid,Product product,TradeType tradeType) throws UnifiedorderRespUnlegalSign{
        
        String remoteAddr = req.getRemoteAddr();
        String reqUrl = req.getRequestURL().toString();
        String payNotifyUrl = reqUrl.substring(0,reqUrl.lastIndexOf("/")) + "/"+PathDefine.PAYED_PATH+".wx";
        
        
        
        UnifiedorderReq unifiedorderReq = getUnifiedorderReq(openid,product,payNotifyUrl,remoteAddr,tradeType);
        logger.debug("发送的统一下单请求参数如下\r\n" + unifiedorderReq);
        String xmlStr = new HttpTookit().doPost(url,unifiedorderReq.toString(),null,null,"UTF-8");
        
        
        
        UnifiedorderResp unifiedorderResp = XStreamHelper.toBean(xmlStr, UnifiedorderResp.class);
        logger.debug("接收统一下单应答内容如下\r\n" + unifiedorderResp);
        
        if(!unifiedorderResp.islegalSign(Config.apikey)){
            throw new UnifiedorderRespUnlegalSign();
        }
        
        Result result = new Result();
        result.setPrepayid(unifiedorderResp.getPrepay_id());
        result.setOrderid(unifiedorderReq.getOut_trade_no());
        
        return result;
    }
    
    
    
    
    
    
    
    
    
    private static UnifiedorderReq getUnifiedorderReq(String openid,Product product,String payNotifyUrl,String remoteAddr,TradeType tradeType) {
        
        UnifiedorderReq unifiedorderReq = new UnifiedorderReq();
        unifiedorderReq.setOpenid(openid);
        unifiedorderReq.setAppid(Config.appid);
        unifiedorderReq.setMch_id(Config.mch_id);
        unifiedorderReq.setProduct_id(product.getProductid());
        unifiedorderReq.setTime_start(DateUtil.getCurDateTimeFormat(DateUtil.DATE_FORMAT_COMPACTFULL));
        try {
            unifiedorderReq.setTime_expire(DateUtil.afterNMinutesDate(unifiedorderReq.getTime_start(), unified_order_time_expire, DateUtil.DATE_FORMAT_COMPACTFULL));
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        unifiedorderReq.setNonce_str(RandomUtil.getRandomStr(32));
        unifiedorderReq.setFee_type("CNY");
        if(tradeType == TradeType.JSAPI){
            unifiedorderReq.setTrade_type("JSAPI");
        }
        if(tradeType == TradeType.NATIVE){
            unifiedorderReq.setTrade_type("NATIVE");
        }
        
        
        //订单号
        unifiedorderReq.setOut_trade_no(System.currentTimeMillis()/1000 + RandomUtil.getRandomNumber(22));
        
        unifiedorderReq.setBody(product.getBody());
        unifiedorderReq.setDetail(product.getDetail());
        unifiedorderReq.setAttach("noAttach");
        unifiedorderReq.setTotal_fee(product.getFee());
        unifiedorderReq.setNotify_url(payNotifyUrl);
        unifiedorderReq.setDevice_info("WEB");
        unifiedorderReq.setSpbill_create_ip(remoteAddr);
        unifiedorderReq.setGoods_tag("");
        unifiedorderReq.setLimit_pay("no_credit");
        
        try {
            unifiedorderReq.setSign(Signature.getSign(unifiedorderReq,null, Config.apikey));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        
        
        return unifiedorderReq;
    }
    
    
    
    public static class UnifiedorderRespUnlegalSign extends Exception{

        private static final long serialVersionUID = 4525489381606735161L;
        
        public UnifiedorderRespUnlegalSign(){
            super();
        }
        public UnifiedorderRespUnlegalSign(String message){
            super(message);
        }
    }
    
    
    
    public static class Result{
        private String orderid;
        private String prepayid;
        
        public String getOrderid() {
            return orderid;
        }
        
        public void setOrderid(String orderid) {
            this.orderid = orderid;
        }
        
        public String getPrepayid() {
            return prepayid;
        }
        
        public void setPrepayid(String prepayid) {
            this.prepayid = prepayid;
        }
    }
    
    public static enum TradeType{
        NATIVE,
        JSAPI
    }
}
